package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.domain.User;
import com.example.demo.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 用户controller
 */
@RestController
@Slf4j
@RequestMapping(value = "user")
@Api(value = "swagger测试")
public class UserController {

    private static final int  BUFFER_SIZE = 2 * 1024;

    @Resource
    UserService userService;

    /**
     * 返回前台页面
     * @return
     */
    @GetMapping(value = "/indexPage")
    public ModelAndView indexPage(){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("index");
        return mv;
    }

    /**
     * 获取用户列表
     * @return
     */
    @ApiOperation(value = "获取用户列表", notes = "以实体类为参数，注意用户名和邮箱不要重复")
    @GetMapping(value = "/list")
    public PageInfo<User> list(@RequestParam("pageNum") int pageNum,
                            @RequestParam("pageSize") int pageSize){
        PageHelper.startPage(pageNum,pageSize);
        List<User> userList = userService.list(new QueryWrapper<User>().select("id"));
        PageInfo<User> pageInfo = new PageInfo<>(userList);
        return pageInfo;
    }

    /**
     * 获取用户单条信息
     * @return
     */
    @GetMapping(value = "/getOne/{id}")
    public User getOne(@PathVariable("id") Integer id){
        return userService.getById(id);
    }

    @GetMapping(value = "/export")
    public void export() throws IOException {
        List<File> fileList = new ArrayList<>();
        for (int i = 0; i < 2; i++) {
            Workbook workbook = new HSSFWorkbook();
            Sheet sheet = workbook.createSheet("Test");
            Row row = sheet.createRow(0);
            for (int j = 0; j <= 2; j++) {
                Cell cell = row.createCell(j);
                cell.setCellType(Cell.CELL_TYPE_STRING);
                cell.setCellValue("第" + (j + 1) + "行");
            }
            row = sheet.createRow(1);
            for (int j = 0; j <= 2; j++) {
                Cell cell = row.createCell(j);
                cell.setCellType(Cell.CELL_TYPE_STRING);
                cell.setCellValue(j + 1);
            }
            String fileName = "表" + (i + 1) + ".xls";
            File file = new File(fileName);
            try {
                FileOutputStream out = new FileOutputStream(file.getPath());
                workbook.write(out);
                out.close();
            } catch (Exception e) {
                System.out.println("出现异常");
                e.printStackTrace();
            }
            fileList.add(file);
        }
        toZip(fileList,new FileOutputStream(new File("D:/test.zip")));
    }


//    /**
//     * 多个文件打包zip下载
//     * @param fileList
//     * @param zipName
//     * @param response
//     * @throws IOException
//     */
//    private void downloadZip(List<File> fileList, String zipName, HttpServletResponse response) throws IOException {
//        if (null == fileList || fileList.size() <= 0) {
//            return;
//        }
//        //将多个文件压缩成一个zip包
//        String zipFilePath = zipName + ".zip";
//        File filePath  = new File(zipFilePath);
//        if (!filePath.isDirectory()) {
//            filePath.mkdirs();
//        }
//        File zipFile = new File(zipFilePath);
//        if (!zipFile.exists()) {
//            zipFile.createNewFile();
//        }
//        getZip(fileList, zipFilePath);
//        downloadFile(zipFile, response);
//    }

//    /*
//    压缩为ZIP
//     */
//    private void getZip(List<File> files, String zipFilePath) throws IOException {
//        FileInputStream in = null;
//        FileOutputStream out = null;
//        ZipOutputStream zipOut = null;
//        List<String> entryNames = new ArrayList<>();
//        try {
//            out = new FileOutputStream(zipFilePath);
//            zipOut = new ZipOutputStream(out, Charset.forName("GBK"));
//            byte[] buffer = new byte[1024];
//            String entryName = "";
//            int seq = 0;
//            for (File f : files) {
//                seq++;
//                in = new FileInputStream(f);
//                //如果待压缩的文件名存在相同的，则先重命名
//                entryName = f.getName();
//                if (entryNames.contains(entryName)) {
//                    int lastIndexOf = entryName.lastIndexOf(".");
//                    if (lastIndexOf != -1) {
//                        String name = entryName.substring(0, lastIndexOf);
//                        String suffix = entryName.substring(lastIndexOf + 1, entryName.length());
//                        entryName = name + "(" + seq + ")" + "." + suffix;
//                    } else {
//                        entryName += "(" + seq + ")";
//                    }
//                }
//                entryNames.add(entryName);
//                ZipEntry entry = new ZipEntry(entryName);
//                zipOut.putNextEntry(entry);
//                int nNumber;
//                while ((nNumber = in.read(buffer)) != -1) {
//                    zipOut.write(buffer, 0, nNumber);
//                }
//                zipOut.closeEntry();
//            }
//        } catch (Exception e) {
//            System.out.println("压缩ZIP包出现异常");
//            e.printStackTrace();
//        } finally {
//            in.close();
//            out.close();
//            zipOut.close();
//        }
//    }


    /**
     * 压缩成ZIP
     * @param srcFiles 需要压缩的文件列表
     * @param out      压缩文件输出流
     * @throws RuntimeException 压缩失败会抛出运行时异常
     */
    public static void toZip(List<File> srcFiles , OutputStream out) throws RuntimeException {
        ZipOutputStream zos = null ;
        try {
            zos = new ZipOutputStream(out);
            for (File srcFile : srcFiles) {
                byte[] buf = new byte[BUFFER_SIZE];
                zos.putNextEntry(new ZipEntry(srcFile.getName()));
                int len;
                FileInputStream in = new FileInputStream(srcFile);
                while ((len = in.read(buf)) != -1){
                    zos.write(buf, 0, len);
                }
                zos.closeEntry();
                in.close();
            }
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils",e);
        }finally{
            if(zos != null){
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /*
    下载文件
     */
    private void downloadFile(File file, HttpServletResponse response) throws IOException {
        String fileName = file.getName();
        InputStream fis = null;
        try {
            fis = new FileInputStream(file);
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/force-download"); // 设置强制下载不打开
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName); // 设置文件名
            response.setHeader("Content-Length", String.valueOf(file.length()));
            byte[] b = new byte[1024];
            int len;
            while ((len = fis.read(b)) != -1) {
                response.getOutputStream().write(b, 0, len);
            }
            response.flushBuffer();
        } catch (IOException e) {
            System.out.println("下载出现异常");
            e.printStackTrace();
        } finally {
            fis.close();
        }
    }
}
